package com.example.socketclient;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SocketActivity extends AppCompatActivity {
    private static final String TAG = "SocketActivity";
    private static final int MESSAGE_RECEIVE_NEW_MSG = 1;
    private static final int MESSAGE_SOCKET_CONNECTED = 2;

    private Button btn;
    private TextView tvMessage;
    private EditText etMessage;

    private Socket mSocket;
    private PrintWriter mPrintWriter;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_RECEIVE_NEW_MSG:
                    tvMessage.setText(tvMessage.getText().toString().trim() + msg.obj + "\n ");
                    break;
                case MESSAGE_SOCKET_CONNECTED:
                    btn.setEnabled(true);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket);
        tvMessage = (TextView) findViewById(R.id.tv_message);
        etMessage = (EditText) findViewById(R.id.et_message);
        btn = (Button) findViewById(R.id.bn_send);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final String msg = etMessage.getText().toString().trim();
                        if (mPrintWriter != null) {
                            mPrintWriter.println(msg);
                            String time = formatDateTime(System.currentTimeMillis());
                            final String showMsg = "self " + time + ":" + msg + " \n ";
                            SocketActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tvMessage.setText(tvMessage.getText().toString().trim() + showMsg);
                                    etMessage.setText("");
                                }
                            });
                        }
                    }
                }).start();
            }
        });

        Intent intent = new Intent();
        intent.setPackage("com.example.testing.ipcdemo");
        intent.setAction("com.example.testing.ipcdemo.TCPServerService");
        startService(intent);

       new Thread(new Runnable() {
            @Override
            public void run() {
                connectTCPServer();
            }
        }).start();
    }

    private String formatDateTime(long time) {
        return new SimpleDateFormat("(HH:mm:ss)").format(new Date(time));
    }

    private void connectTCPServer() {
        Socket socket = null;
        while (socket == null) {
            try {
                socket = new Socket("localhost", 8688);
                mSocket = socket;
                mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                mHandler.sendEmptyMessage(MESSAGE_SOCKET_CONNECTED);
                Log.e(TAG, "run: connect server success");

            } catch (IOException e) {
                SystemClock.sleep(1000);
                Log.e(TAG, "run: connecttcp server failed,retry");
                e.printStackTrace();
            }
        }

        // 接收服务端的消息
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (!SocketActivity.this.isFinishing()) {
                String msg = br.readLine();
                Log.e(TAG, "run: receive:" +msg);
                if (msg != null) {
                    String time = formatDateTime(System.currentTimeMillis());
                    final String showMsg = "server " + time + ":" + msg + "\n";
                    mHandler.obtainMessage(MESSAGE_RECEIVE_NEW_MSG, showMsg).sendToTarget();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        mPrintWriter.close();
        try {
            br.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.e(TAG, "connectTCPServer: quit");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSocket != null) {
            try {
                mSocket.shutdownInput();
                mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
